<template>
    <div class="container gen-three-order">
        <div class="file-upload-container" v-if="status==0">
            <el-upload
                ref="upload"
                action="/"
                drag
				multiple
                accept=".xlsx, .xlsm, .xls"
                :auto-upload="false"
                :on-change="handleChange"
				show-file-list>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip" slot="tip">只能上传excel文件</div>
            </el-upload>
            <div class="begin-btn">
                <el-button type="primary" @click="handleBegin" :disabled="!hasFile" v-if="status==0">开始解析</el-button> 
            </div>
        </div>
		<div class="tpl-container" v-if="status==1">
			<div class="left">
				<el-tabs v-model="configName">
					<el-tab-pane label="内容设置" name="content">
						<json-form
						 ref="orderForm"
						 :options="contentOptions"
						 direction="h"
						 :form="form"  v-viewer>
							<template v-slot:img="{data}">
								<img width="50" height="50" :src="data | getFilePath"/>
							</template>
							<template v-slot:imgList="{data}">
								<div class="row-image">
									<img width="50" height="50" :src="item | getFilePath" v-for="item in data" :key="item" />
									<!-- <img width="50" height="50" :src="item | getFilePath" v-for="item in data" :key="item" /> -->
								</div>
							</template>
						</json-form>
						<div class="bottom-btn-groups">
							<div class="ipt-wrap">
								<span>共{{importArrs.length}}条数据 跳到</span>
								<span class="ipt">
									<el-input v-model="jump" 
									:max="importArrs.length || 1"
									:min="1"
									@change="handleJump"
									size="mini" type="number"></el-input>
								</span>
							</div>
							<el-button :disabled="!hasPrev" type="warning" @click="handlePrev" size="mini" icon="el-icon-arrow-left">
								
							</el-button>
							<div style="margin: 0 10px;">{{ currentIndex }}</div>
							<el-button :disabled="!hasNext"  type="warning" @click="handleNext" size="mini" icon="el-icon-arrow-right">
							</el-button>
							<el-button 
								@click="handleSubmit"
								size="mini"
								type="primary">
								保存当前订单
							</el-button>
							<el-button 
								@click="autoGenerate"
								size="mini"
								type="danger">
								保存所有订单
							</el-button>
							<el-button @click="handleBack" size="mini">
								返回
							</el-button>
						</div>
						
					</el-tab-pane>
				</el-tabs>
				<div class="err-log">
					<div class="log" v-for="item in errorLogs" :key="item">
						{{ item }}
					</div>
				</div>
			</div>
		</div>
    </div>
</template>
<script>
import ImagePreview from "@/components/image-preview.vue"
import jsonForm from "@/components/json-form.vue"
import text from "@/components/text.vue"
import {dataURLtoFile, readFile} from "@/util/fileUtil"
import {uploadMode,uploadModeType} from "@/config/upload"
import {import2AddOrder} from "@/apis/order"
import {cnKeyJson2en} from "./format"
import html2canvas from "html2canvas"
import * as XLSX from "xlsx"
import dayjs from "dayjs"
export default{
	components:{
		jsonForm,
		text,
		ImagePreview
	},
	data(){
		return {
			status:0,
			hasFile:false,
			jump:null,
			form:{
				bid:"XXYX170252256516693034406189",
				orderId:"300860500410999384",
				money:"25",
				orderNo:"300860500410999384",
				orderCreateTime:"2023-12-19 13:48:28",
				shopName:"金汤铺炖汤世家（六里桥店）",
				platform:"美团",
				imgList:[],
				nickname:"dj"
			},
			configName:"content",
			// platform:"mt",
			isDraw:true,
			// myImage:"",
			platformOptions:{
				ele:[
					{
						key:"bid",
						type:"el-input",
						label:"账单编号",
						// width:250,
						required:true
					},
					{
						key:"orderNo",
						type:"el-input",
						label:"平台订单号",
						required:true
					},
					{
						key:"orderId",
						type:"el-input",
						label:"订单Id",
						required:true
					},
					{
						key:"amount",
						type:"el-input",
						label:"实际金额",
						required:true
					},
					{
						key:"money",
						type:"el-input",
						label:"结算金额",
						required:true
					},
					{
						key:"orderCreateTime",
						type:"el-date-picker",
						label:"下单时间",
						required:true,
						props:{
							type:"datetime",
							format:"yyyy-MM-dd HH:mm:ss",
							"value-format":"yyyy-MM-dd HH:mm:ss"
						}
					},
					{
						key:"imgList",
						slot:"imgList",
						label:"订单截图",
					}
				],
				mt:[
					{
						key:"bid",
						type:"el-input",
						label:"账单编号",
						// width:250,
						required:true
					},
					{
						key:"orderNo",
						type:"el-input",
						label:"平台订单号",
						required:true
					},
					{
						key:"orderId",
						type:"el-input",
						label:"订单Id",
						required:true
					},
					{
						key:"amount",
						type:"el-input",
						label:"实际金额",
						required:true
					},
					{
						key:"money",
						type:"el-input",
						label:"结算金额",
						required:true
					},
					{
						key:"orderCreateTime",
						type:"el-date-picker",
						label:"下单时间",
						required:true,
						props:{
							type:"datetime",
							format:"yyyy-MM-dd HH:mm:ss",
							"value-format":"yyyy-MM-dd HH:mm:ss"
						}
					},
					{
						key:"imgList",
						slot:"imgList",
						label:"订单截图",
					}
				],
				jd:[
					{
						key:"bid",
						type:"el-input",
						label:"账单编号",
						// width:250,
						required:true
					},
					{
						key:"orderNo",
						type:"el-input",
						label:"平台订单号",
						required:true
					},
					{
						key:"orderId",
						type:"el-input",
						label:"订单Id",
						required:true
					},
					{
						key:"amount",
						type:"el-input",
						label:"实际金额",
						required:true
					},
					{
						key:"money",
						type:"el-input",
						label:"结算金额",
						required:true
					},
					{
						key:"orderCreateTime",
						type:"el-date-picker",
						label:"下单时间",
						required:true,
						props:{
							type:"datetime",
							format:"yyyy-MM-dd HH:mm:ss",
							"value-format":"yyyy-MM-dd HH:mm:ss"
						}
					},
					{
						key:"imgList",
						slot:"imgList",
						label:"订单截图",
					}
				]
			},
			
			mtOperationBtns:[
				// {
				// 	label:"打赏骑手",
				// 	image:require("@/assets/image/mt/mt_111.png")
				// },
				// {
				// 	label:"打赏骑手",
				// 	image:require("@/assets/image/mt/mt_111.png")
				// }
			],
			importArrs:[],
			currentIndex:1,
			errorLogs:[],
			genBidObj:{},
		}
	},
	methods:{
		handleChange(file){
			console.log(file)
			this.hasFile = this.$refs.upload.uploadFiles.length>0
		},
		async handleBegin(){
			console.log("解析文件")
			let files = this.$refs.upload.uploadFiles
			console.log(files)
			for(let i = 0;i<files.length;i++){
				let dataBinary = await readFile(files[i].raw)
				let workBook = XLSX.read(dataBinary, { type: "binary", cellDates: true })
				let workSheet = workBook.Sheets[workBook.SheetNames[0]]
				console.log(workSheet)
				// console.log(workSheet)
				// const data = XLSX.utils.sheet_to_json(workSheet,{header:1,range:1})
				let data = XLSX.utils.sheet_to_json(workSheet,{raw:false})
				console.log(data)
				data = cnKeyJson2en(data)
				console.log(data)//这里已经能拿到转换后的json
				let {data:fileObj} = await this.getExcelImage(files[i].raw)
				// console.log(fileObj)
				for(let key in fileObj ){
					// console.log(key)
					data[key-1].imgList = fileObj[key]
				}
				console.log(data)//这里已经能拿到转换后的json
				this.importArrs = this.importArrs.concat(data)
			}
			if(this.importArrs.length==0){
				this.$message.error("excel数据为空")
				return
			}
			this.parseImportData()
			this.form = this.importArrs[this.currentIndex-1]
			this.status = 1
		},
		parseImportData(){
			let genBidObj = {}
			this.importArrs.forEach(item=>{
				genBidObj[item.shopName] || (genBidObj[item.shopName] = {})
				genBidObj[item.shopName][item.platform] || (genBidObj[item.shopName][item.platform]=item.orderId)
			})
			console.log(genBidObj)
			this.genBidObj = genBidObj
			this.importArrs = this.importArrs.map(item=>{
				if(!item.bid){
					item.bid = this.genBidObj[item.shopName][item.platform]
				}
				return item
			})
		},
		async autoGenerate(){
			for(let i = 0;i<this.importArrs.length;i++){
				console.log(i,this.importArrs.length)
				this.currentIndex = i+1
				this.form = this.importArrs[i]
				// await this.sleep(1000)
				// await this.generatePic()
				// await this.sleep(500)
				await this.handleSubmit()
				// await this.sleep(500)
				// await this.sleep(500)
			}
			this.currentIndex = this.importArrs.length
		},

		async handleSubmit(){
			//构造订单数据
			let {
				bid,
				orderId,
				orderNo,
				money,
				amount,
				orderCreateTime,
				imgList,
				shopName,
				platform
			} = this.form
			let data = {
				bid,
				orderId,
				orderNo,
				money,
				amount,
				orderCreateTime,
				imgList,
				shopName,
				platform:platform=="美团"?1:(platform.includes("京东")?3:2),
				activeDate:dayjs(this.form.orderCreateTime).format("YYYY-MM-DD")

			}
			console.log(data)
			try {
				await import2AddOrder(data)
			} catch (error) {
				console.log(error)
				if(error.message){
					this.errorLogs.push("平台订单号:"+orderNo+" "+error.message)
				}
			}
		},
		handleNext(){
			if(this.hasNext){
				if(this.currentIndex>this.importArrs.length || this.currentIndex<1){
					this.currentIndex = this.importArrs.length
					return
				}
				this.currentIndex = this.currentIndex+1
				this.refreshPage()
			}
		},
		handlePrev(){
			if(this.hasPrev){
				if(this.currentIndex>this.importArrs.length || this.currentIndex<1){
					this.currentIndex = 1
					return
				}
				this.currentIndex = this.currentIndex-1
				this.refreshPage()
			}
		},
		handleJump(page){
			page = page - 0
			if(page<1||page>this.importArrs.length){
				this.$message.error("页码错误")
				this.jump = null
				return
			}
			this.currentIndex = page
			this.form = this.importArrs[page-1]
			this.jump = null
			
		},
		refreshPage(){
			this.form = this.importArrs[this.currentIndex-1]
			// this.generatePic()
		},
		sleep(time=1000){
			return new Promise((resolve)=>{
				setTimeout(()=>{
					resolve()
				},time)
			})
		},
		handleBack(){
			this.status = 0
			this.importArrs = []
			this.currentIndex = 1
			this.errorLogs = []
		},
		async getExcelImage(file){
			let currentUploadMod = uploadModeType[uploadMode]
			let res = await currentUploadMod.upload(this.parseImageAction,file,{
				key:"type",
				value:"images/parseExcel"
			})
			console.log(res)
			return res
		}
	},
	computed:{
		platform(){
		 
			if(this.form.platform.includes("美团")){
				return "mt"
			}
			else if(this.form.platform.includes("京东")){
				return "jd"
			}
			else{
				return "ele"
			}
		},
		contentOptions(){
			return this.platformOptions[this.platform]
		},
		action(){
			return process.env.VUE_APP_UPLOAD_URL + "/image"
		},
		parseImageAction(){
			return process.env.VUE_APP_REQUEST_URL + "order/parseImage"
		},
		hasNext(){
			return this.currentIndex < this.importArrs.length
		},
		hasPrev(){
			return this.currentIndex > 1
		},
		excelSrc(){
			let mode = process.env.NODE_ENV
			let src = "/"
			if(mode=="production"){
				src = "./"
			}
			return src + "excel/tpl.xlsx"
		}
	},
	watch:{
		// currentIndex(newval,oldval){
		// 	console.log(newval,oldval)
		// 	if(this.status==1){
		// 		if(newval>this.importArrs.length || newval < 1){
		// 		// this.$message.error("跳转错误")
		// 			return
		// 		}
		// 		this.form = this.importArrs[newval-1]
		// 	}
		// }
	}
}
</script>
<style lang="less" scoped>
.file-upload-container{
    display: flex;
    justify-content: center;
    .begin-btn{
        margin-left: 20px;
    }
}
.gen-three-order{
	// min-height: 125%;
	.tpl-container{
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: row;
		.left{
			// flex: 1;
			// width: calc(100% - @phone-width / 2);
			padding: 0 20px 0 0;
			.bottom-btn-groups{
				font-size: 14px;
				display: flex;
				align-items: center;
				.ipt-wrap{
					display: flex;
					align-items: center;
					margin-right: 10px;
					.ipt{
						width: 100px;
						margin-left: 10px;
					}
				}
			}
			.row-image{
				// display: flex;
				// align-items: center;
				&>img{
					margin-right: 10px;
				}
			}
			.err-log{
				margin-top: 20px;
				font-size: 12px;
				color: #666;
			}
		}
	}
}

</style>